<!--数据权限页面-->
<template>
  <a-card style="background-color: #FFF !important;">
    <div class="totalView">
      <!--      左-->
      <div class="left">
        <vxe-grid
          ref="xGrid"
          size="mini"
          :border="true"
          :resizable="true"
          :showOverflow="true"
          :loading="loading"
          :height="pageHeight-102"
          :align="left"
          :columns="columns1"
          :data="dataSource"
          :treeConfig="treeConfig"
          @radio-change="radioChangeEvent"
          v-bind="vexConfig"
          :radio-config="{ trigger: 'row',highlight: true}"
        >
          <template #pager>
            <vxe-pager
              :layouts="['Total', 'PrevPage', 'Number', 'NextPage',]"
              :currentPage.sync="ipagination.current"
              :page-size.sync="ipagination.pageSize"
              :total="ipagination.total"
              :pageSizes="ipagination.pageSizeOptions"
              @page-change="handlePageChange">
            </vxe-pager>
          </template>
        </vxe-grid>
      </div>
      <!--      右-->
      <div class="right">
        <a-spin :spinning="confirmLoading" style="width: 33.33%;margin: 0 8px;">
          <div class="menuTitle" style="min-height: 160px;text-align: left;">
            <div class="menuStyle">菜单</div>
            <span v-if="this.selectedRowKeys.length ==0 || !this.selectedRowKeys.length">请点击选择角色</span>
            <div v-else class="menuList">
              <a-menu
                style="width:100%;background-color: #FFF"
                mode="inline"
                theme="light"
                @click="menuClick"
              >
                <a-sub-menu v-for="(item,index) in treeData" :key="item.functionCode" @titleClick="menuClick">
                  <span slot="title"><a-icon :type="item.icon"/><span>{{ item.name }}</span></span>
                  <a-sub-menu @titleClick="menuClick" v-for="(items,index) in item.children" :key="items.functionCode">
                    <span slot="title"><a-icon :type="items.icon"/><span>{{ items.name }}</span></span>
                    <a-menu-item v-for="(itemss,index) in items.children" :key="itemss.functionCode">
                      {{ itemss.name }}
                    </a-menu-item>
                  </a-sub-menu>
                </a-sub-menu>
              </a-menu>
            </div>
          </div>
        </a-spin>
        <!--        table 1 -->
        <div style="width: 33.33%;margin: 0 8px 0 0">
          <vxe-grid
            ref="xGrid"
            size="mini"
            :border="true"
            :resizable="true"
            :showOverflow="true"
            :loading="loading"
            :height="pageHeight-102"
            :align="left"
            :columns="columns2"
            :data="dataSource2"
          >
            <template #permName="{ row }">
              <a @click="searchTable2(row)">{{ row.permName }}</a>
            </template>
            <template #action="{ row }">
              <a @click="handleToEdit(row)">编辑</a>
            </template>
            <template #actionHeader>
              <span style="display: flex;justify-content: space-between;align-items: center; margin: 0;">
                <div style="line-height:3px">
                  权限名称
                </div>
                 <a-tag @click="handleHttp">新增</a-tag>
              </span>
            </template>
            <template #pager>
              <vxe-pager
                :layouts="['Total', 'PrevPage', 'Number', 'NextPage',]"
                :currentPage.sync="ipagination2.current"
                :page-size.sync="ipagination2.pageSize"
                :total="ipagination2.total"
                :pageSizes="ipagination2.pageSizeOptions"
                @page-change="handlePageChange2">
              </vxe-pager>
            </template>

          </vxe-grid>
        </div>

        <!--        table2-->
        <div style="width: 33.33%">
          <vxe-grid
            ref="xGrid3"
            size="mini"
            :border="true"
            :resizable="true"
            :showOverflow="true"
            :loading="loading"
            :height="pageHeight-138"
            :align="left"
            :columns="columns"
            :data="dataSource1"
            @radio-change="radioChangeEvent2"
            :radio-config="{ trigger: 'row',highlight: true}"
            v-bind="vexConfig"
          >
            <template #actionHeader>
              <a-tag @click="doEdit">确认</a-tag>
            </template>
          </vxe-grid>
        </div>
      </div>
    </div>
    <formItems ref="modalForm" @okpopup="modalFormOk" v-bind="configw"></formItems>
    <!--    <Modal ref='permodalForm' @polocyOk='saveUserRelation'></DataPermissionModal>-->
    <!--    <orgtoUser ref='orgtoUser' @ok='saveUserRelation'></orgtoUser>-->
  </a-card>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { PageListMixin } from '@/mixins/PageListMixin'
import search from '@comp/view/base-crud/search/Search'
import DataPermissionModal from '@page-modules/DataPermissionModal'
import formItems from '@comp/cn-components/FormItems'
import Vue from 'vue'

export default {
  name: 'dataPermission',
  description: '数据权限页面',
  mixins: [PageListMixin],
  components: {
    search,
    DataPermissionModal,
    formItems
  },
  data() {
    return {
      name: '',
      loadings: false,
      ipagination: {
        current: 1,
        size: 20,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        simple: true,
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      ipagination2: {
        current: 1,
        size: '10',
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      ipagination3: {
        current: 1,
        size: '10',
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      columns2: [
        {
          title: '权限名称',
          align: 'left',
          field: 'permName',
          minWidth:108,
          slots: { default: 'permName',  header: 'actionHeader' }
        },
        {
          title: '操作',
          field: 'action',
          align: 'left',
          slots: {
            default: 'action',
          },
        }
      ],
      selectedRowKeys3: [],
      selectionRows3: [],
      selectedRowKeys2: [],
      selectionRows2: [],
      dataSource2: [],
      functionCode: null,
      confirmLoading: false,

      selectedRowKeys: [],
      selectedRows: [],
      dataSource1: [],
      dataModal: {
        code: '',
        name: ''
      },
      description: '企业组织页面',
      checkedKeys: [],
      treeData: [],
      autoExpandParent: false,
      queryParam: {},
      //列设置
      settingColumns: [],
      // 列定义
      columns: [
        {
          type: 'radio',
          minWidth: 60,
          width: 60,
          fixed: 'left',
          slots: {
            header: 'actionHeader'
          },
        },
        {
          title: '权限标记',
          field: 'dataTypeName',
        }
      ],
      columns1: [
        { type: 'radio', width: 60, fixed: 'left' },
        {
          title: '角色编号',
          field: 'roleCode'
        },
        {
          title: '角色名称',
          field: 'roleName',
        }
      ],
      url: {
        list: window._CONFIG['domianURL'] + '/cnRoleController/getRoleList',
        treeList: window._CONFIG['domianURL'] + '/cnFunctionController/findTreeByRoleCodeList',
        roleSearch: window._CONFIG['domianURL'] + '/sysDataPermsController/findList',
        doSelect: window._CONFIG['domianURL'] + '/sysDataPermsController/doSelect',
        roleList: window._CONFIG['domianURL'] + '/sysDataPermsController/findSelectList',
        saveObjs: window._CONFIG['domianURL'] + '/sysDataPermsController/saveOrUpdateObj',
        editpermiss: window._CONFIG['domianURL'] + '/sysDataPermsController/getDataPermsObjById',

        startOrStopUrl: window._CONFIG['domianURL'] + '/price/startOrStop',
        deleteBatch: '/test/cn-formDemo/deleteBatch',
        exportXlsUrl: '/test/cn-formDemo/exportXls'
      },
      searchConfig: [
        {
          type: 'input',
          name: 'orgCode',
          placeholder: '组织编号'
        },
        {
          type: 'input',
          name: 'orgName',
          placeholder: '组织名称'
        },
        {
          dictCode: 'org_type',
          type: 'j-select',
          name: 'orgType',
          placeholder: '组织类型'
        }
        // {
        //   // label:'下单时间',
        //   type:'date',
        //   name:'orderDate',
        //   placeholder:'下单时间',
        //   toggleSearchStatus:true
        //
        // },
      ]
    }
  },
  methods: {
    radioChangeEvent({ row }) {
      this.selectionRows = [row]
      this.selectedRowKeys = [row[this.tableKey]]
      this.sendRoleId(row)
    },
    radioChangeEvent2({ row }) {
      this.selectionRows2 = [row]
      this.selectedRowKeys2 = [row['dataType']]
    },
    // table2
    searchTable2(r) {
      if (this.selectedRowKeys.length == 0) {
        this.$message.info('请先选择角色')
        return
      }
      if (this.functionCode == null) {
        this.$message.info('请先选择一行菜单')
        return
      }
      if(r){
        this.selectedRowKeys3 = [r[[this.tableKey]]]
        this.selectionRows3 = [r]
      }
      let record = {
        functionCode: this.functionCode,
        roleCode: this.selectionRows[0].roleCode,
        permFlag: r.permFlag
      }
      this.loading = true
      postAction(this.url.roleSearch, { ...record }).then((res) => {
        if (res.success) {
          this.dataSource1 = res.result
          this.selectedRowKeys2 = []
          this.selectionRows2 = []
          let a = []
          let b = []
          res.result.forEach(item => {
            if (item.isCheck == 1) {
              a.push(item.dataType)
              b.push(item)
            }
          })
          const $grid = this.$refs.xGrid3
          $grid && $grid.setRadioRow(b[0]||{})
          this.$set(this, 'selectedRowKeys2', a)
          this.$set(this, 'selectionRows2', b)
          this.ipagination2.total = res.result.total || 0
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    handleToEdit(record) {
      if (this.selectedRowKeys.length == 0) {
        this.$message.info('请先选择角色')
        return
      }
      if (this.functionCode == null) {
        this.$message.info('请先选择一行菜单')
        return
      }
      getAction(this.url.editpermiss, { id: record.id }).then(res => {
        if (res.success) {
          record = res.result
          this.luyouid = false
          this.name = '编辑接口'
          this.$refs.modalForm.fornOn(record)
        } else {
          this.$message.info(res.message)
        }
      })

    },
    handlePageChange2(pagination, filters, sorter) {
      this.ipagination2.currentPage = currentPage
      this.ipagination2.pageSize = pageSize
      this.searchRoleList()
    },
    handleHttp(cord) {
      if (this.selectedRowKeys.length == 0) {
        this.$message.info('请先选择角色')
        return
      }
      if (this.functionCode == null) {
        this.$message.info('请先选择一行菜单')
        return
      }
      this.luyouid = false
      this.name = '新增接口'
      this.$refs.modalForm.fornOn()
    },
    modalFormOk(cord, pattern, model) {
      console.log(cord, pattern, model)
      let record = {
        functionCode: this.functionCode,
        roleCode: this.selectionRows[0].roleCode,
        dataTypeName: model.dataTypeName,
        id: model.id,
      }
      let param = { ...cord, ...record }
      postAction(this.url.saveObjs, param).then((res) => {
        if (res.success) {
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.searchRoleList()
      })
    },
    searchRoleList() {
      let record = {
        functionCode: this.functionCode,
        roleCode: this.selectionRows[0].roleCode
      }
      this.loadings = true
      postAction(this.url.roleList, { ...record }).then((res) => {
        if (res.success) {
          this.dataSource2 = res.result
          this.ipagination2.total = res.result.total || 0
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loadings = false
      })
    },
    menuClick(e1, e2, e3) {
      console.log(e1, e2, e3)
      this.functionCode = e1.key
      this.dataSource1 = []
      this.selectedRowKeys2 = []
      this.selectionRows2 = []
      this.selectedRowKeys3 = []
      this.selectionRows3 = []
      this.searchRoleList()
    },

    handleAddTable() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.info('请先选择角色')
        return
      }
      if (this.functionCode == null) {
        this.$message.info('请先选择一行菜单')
        return
      }
      let record = {
        functionCode: this.functionCode,
        roleCode: this.selectionRows[0].roleCode,
        roleName: this.selectionRows[0].roleName
      }
      this.$refs.permodalForm.edit(record)
    },
    doEdit() {
      let that = this
      if (this.selectedRowKeys.length == 0) {
        this.$message.info('请先选择角色')
        return
      }
      console.log(this.selectionRows3)
      let record = {
        functionCode: this.functionCode,
        roleCode: this.selectionRows[0].roleCode,
        permFlag: this.selectionRows3[0].permFlag,
        dataTypes: this.selectedRowKeys2
      }
      this.loading = true
      postAction(this.url.doSelect, { ...record }).then(res => {
        if (!res.success) {
          that.$message.error(res.message)
          return
        }
        this.$message.success(res.message)
      }).finally(() => {
        this.loading = false
      })
    },
    onSelectChange3(selectedRowKeys, selectionRows) {
      this.selectedRowKeys3 = selectedRowKeys
      this.selectionRows3 = selectionRows
    },
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    sendRoleId(e1) {
      if (e1) {
        this.selectedRowKeys3 = []
        this.selectionRows3 = []
        this.selectedRowKeys2 = []
        this.selectionRows2 = []
        this.dataSource1 = []
        this.dataSource2 = []
        this.loadTreeData(e1)
      }
    },
    userlist(record, type = 'treeTable', modal = 'orgtoUser') {
      this.$refs[modal].showModal(record)
      return false
    },
    saveUserRelation(cord) {
      if (cord) {
        this.sendRoleId(cord)
      }
    },
    // 加载树数据
    loadTreeData(e) {
      let record = {
        roleCode: e.roleCode
      }
      this.confirmLoading = true
      postAction(this.url.treeList, { ...record }).then(res => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        this.treeData = res.result
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    onSearch() {
      console.log('889')
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    customRowFn(record) {
      return {
        on: {
          click: () => {
            let key = record.id
            this.selectedRowKeys = [key]
            this.selectionRows = [record]
          }
        }
      }
    },
    onClickRow(record, status) {
      return {
        on: {
          click: () => {
            if (status == 3) {
              this.selectedRowKeys3 = [record.permFlag]
              this.selectionRows3 = [record]
            } else if (status == 2) {
              let keys = record.dataType
              if (this.selectedRowKeys2.indexOf(keys) == -1) {
                this.selectedRowKeys2 = [record.dataType]
                this.selectionRows2 = [record]
              } else {
                this.selectedRowKeys2.remove(record.dataType)
                this.selectionRows2.remove(record)
              }
              console.log(this.selectedRowKeys2)
            }
          }
        }
      }
    }
  },

  created() {
  },
  computed: {
    configw() {
      return {
        title: this.name,
        width: 800,
        config: {
          list: [
            {
              label: '接口标记',
              type: 'input',
              disabled: this.luyouid,
              placeholder: '请输入接口标记',
              name: 'permFlag',
              check: { rules: [{ required: true, message: '请输入接口标记' }] }
            },
            {
              disabled: this.luyouid,
              label: '权限名称',
              type: 'input',
              placeholder: '请输入权限名称',
              name: 'permName',
              check: { rules: [{ required: true, message: '请输入权限名称' }] }
            },
            {
              label: '权限对象',
              type: 'j-mut-select',
              dictCode: 'perms_type',
              placeholder: '请选择权限对象',
              name: 'dataType',  // 后台接受字段
              check: { rules: [{ required: true, message: '请选择权限对象' }] }
            }
          ]
        },
        footerButton: this.footerButton
      }
    }
  }
}
</script>

<style scoped lang="less">
@import '~@assets/less/common.less';

.totalView {
  margin-top: 8px;
  display: flex;
  flex-direction: row;

  .left {
    width: 25%;

    .left-header {
      display: flex;
      justify-content: space-around;

      .left-header-text {
        padding: 5px 0 5px 0;
        width: 100%;
        text-align: center;
        font-size: 18px;
        margin-bottom: 26px;

        background-color: #edeff0;
      }
    }

  }


  .right {
    display: flex;
    width: 75%;

    //.table-width {
    //  max-width: calc(100% - 300px - 280px - 50px);
    //  overflow: auto;
    //}

  }
}

.table-page-search-wrapper {

  padding-bottom: 5px;

}

.table-operator {

}

.middleModal {
  position: relative;
  width: 50px;
  margin: 0 5px;
  background-color: rgba(52, 152, 219, .4);

  .middleModalicon {
    position: absolute;
    top: 50%;
    width: 100%;
    font-size: 20px;
    font-weight: 700;
  }
}

.menuTitle {
  border: 1px solid #E8EAEC;
  border-top: none;
  width: 100%;
  height: calc(100vh - 138px);
}

.menuStyle {
  font-size: 12px;
  font-weight: 600;
  height: 36px;
  padding-left: 10px;
  background-color: #F8F8F9;
  line-height: 36px;
  border-bottom: 1px solid #E8EAEC;
  border-top: 1px solid #E8EAEC;
}

.menuList {
  height: calc(100% - 36px);
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  /deep/ .ant-layout-sider {
    background-color: #FFFFFF !important;
  }

  /deep/ .ant-menu {
    background-color: #FFFFFF !important;
  }

}
.ant-tag{
  margin: 0;
  &:hover{
    color: #FFF;
    background-color: @primary-color;
    border-color: @primary-color;
  }
}

</style>